package sorting

import "gitee.com/guuzaa/sorting/constraints"

func CountingSort[T constraints.Integer](nums []T) []T {
	if len(nums) < 2 {
		return nums
	}

	max, min := nums[0], nums[0]
	for _, num := range nums {
		switch {
		case num > max:
			max = num
		case num < min:
			min = num
		}
	}

	counter := make([]int, max-min+1)

	for _, num := range nums {
		counter[num-min] += 1
	}

	j := 0
	for i := 0; i < len(counter); i++ {
		for counter[i] > 0 {
			nums[j] = T(i) + min
			counter[i]--
			j++
		}
	}

	return nums
}
